<!-- 代表作：二供泵房 -->
<script setup>
import { reactive, ref, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { loadUnitPosition, loadBMapGLScript, getMaskOverlay } from '@T2/utils/BMapGL_API.ts';
import { positionApi } from '@T2/service/api.ts';
import { mapStyle } from './mapStyle.js';
import { getLastdata } from '@T2/utils/params.ts';
import NormalPNG from '@T2/assets/maps/buoy-normal.png';
import dayjs from 'dayjs';

let maps = {}, unitList = [];
const Resd = reactive({
  goHomes: 0,
  sensors: [],
  unitList: [],
});
const sensors = ref([]);
onMounted(async () => {
  if (!window.BMapGL) {
    await loadBMapGLScript();
  }
  
  const flag = true;
  // const flag = import.meta.env.MODE !== 'development';
  loadUnitPosition().then(res => {
    // sensorsSetting(res);
    flag && mapsInit(res);
  })
})
const sensorsSetting = (units) => {
  Resd.sensors = [];
  Resd.unitList = [];
  units.forEach(unit => {
    unit._sensors = [];
    if (unit.params) {
      const paramsObj = JSON.parse(unit.params);
      unit._sensors = paramsObj?.sensors || [];
    }
    Resd.sensors.push({c: unit._sensors});
    unit.online = true; //临时
  });
  getLastdata(Resd.sensors)
  Resd.unitList = units;
}
let resetHome = {
  center: {},
  zoom: 11,
};
watch(() => Resd.goHomes, (nv, ov) => {
  maps.centerAndZoom(resetHome.center, resetHome.zoom);
});
const mapsInit = (arrs) => {
  const units = arrs.filter(i => +i.x && +i.y);
  maps = new window.BMapGL.Map('map_container');
  
  let viewPort = {
    center: {lat: 31.13, lng: 121.1},
    zoom: 12,
  }
  if (units.length) {
    console.log('ww')
    viewPort = maps.getViewport(units.map(item => new window.BMapGL.Point(+item.x, +item.y)));
  }
  maps.centerAndZoom(viewPort.center, viewPort.zoom);
  resetHome.center = maps.getCenter();
  resetHome.zoom = maps.getZoom();
  maps.setMapStyleV2({styleJson: mapStyle});
  // getMaskOverlay('青浦区', 1).then(res => {
  //   res?.mapmasks?.forEach(item => maps.addOverlay(item));
  //   res?.borders?.forEach(item => maps.addOverlay(item));
  // });
  maps.setTilt(0);    // 设置地图倾斜角
  maps.setHeading(0); // 设置地图倾斜角
  maps.enableKeyboard();
  maps.enableScrollWheelZoom();
  maps.enableInertialDragging();
  maps.enableContinuousZoom();
  maps.setDisplayOptions({ poi: true, poiIcon: false});
  units.forEach(item => {
    item.collect = true; //临时
    let icon = new window.BMapGL.Icon(NormalPNG, new window.BMapGL.Size(0, 0));
    let marker = new window.BMapGL.Marker(new window.BMapGL.Point(+item.x, +item.y), { icon: icon });
    addClickHandler(marker, item);
    maps.addOverlay(drawMarker(marker, item));
  });
}
const addClickHandler = (marker, item) => {
  marker.addEventListener('click', function (e) {
    openInfoWindow(item);
  });
}
const drawMarker = (marker, item) => {
  setTimeout(() => {
    marker.domElement.innerHtml = marker.domElement.childNodes && marker.domElement.childNodes[0];
    marker.domElement.className = 'map-buoy';
    
    let eleIcon = document.createElement('div');
    eleIcon.className = item.warn_number > 0 ? 'icon alarm' : 'icon';
    marker.domElement.appendChild(eleIcon);
  }, 600);
  return marker;
}
const openInfoWindow = (item) => {
  let point = new window.BMapGL.Point(+item.x, +item.y);
  let content = '';
  const [_sensors0, _sensors1] = item._sensors || [];
  if (_sensors0?.c && _sensors1?.c) {
    content = `
      <div class="${item.warn_number ? 'pop pop_alarm' : 'pop'}">
        <div class="unit_info flex-center-center flex-column">
          <div class="${item.collect ? 'icon' : 'icon icon_no'}"></div>
          <div class="name ellipsis">${ item.name}</div>
          <div class="time">${ dayjs().format('MM-DD HH:mm')}</div>
        </div>
        <div class="datas_info">
          <div class="status-box flex--center">
            泵运行状态：${
              _sensors0.c?.map(c => {
                return `<div class="${ c.value === '运行' ? 'pump' : c.value === '故障' ? 'pump alarm' : 'pump stop'}"></div>`;
              }).join('') || ''
            }
          </div>
          <div class="nums-box flex">
            ${
              _sensors1.c?.map(c => {
                return `
                  <div class="data flex-sb flex-column">
                    ${
                      c.value === '掉线'
                      ? `
                          <span>-</span>
                          <span>${ c.n }</span>
                        `
                      : `
                          <span>${ c.value }(${ c.unit ? c.unit : ''})</span>
                          <span>${ c.n }</span>
                        `
                    }
                  </div>
                `;
              }).join('')
            }
          </div>
        </div
      </div>
    `;
  } else {
    content = `
      <div class="${item.warn_number ? 'pop pop_alarm' : 'pop'}">
        <div class="unit_info flex-center-center flex-column">
          <div class="${item.collect ? 'icon' : 'icon icon_no'}"></div>
          <div class="name ellipsis">${ item.name}</div>
          <div class="time">${ dayjs().format('MM-DD HH:mm')}</div>
        </div>
        <div class="datas_info">
          
        </div
      </div>
    `;
  }
  let infoWindow = new window.BMapGL.InfoWindow(content, {
    width: 0,
    offset: new window.BMapGL.Size(-29, 0), //默认的一个引导箭头,宽58px,高31px,往左偏移一半宽度
  });
  maps.openInfoWindow(infoWindow, point);
}

/* 地理位置相关 */
const getPosition = () => {
  return new Promise((resolve, reject) => {
    positionApi({
      method: 'get',
      params: {
        ordering: 'id',
      }
    }).then(res => {
      resolve(res.results || []);
    }).catch(e => {
      reject(e);
    });
  });
}
</script>

<template>
  <div id="map_container" class="BMap_container"></div>
  <img class="left" :src="require('./assets/left.png')" />
  <img class="right" :src="require('./assets/right.png')" />
</template>

<style lang="scss" scoped>
@use './style/buoyPop.scss';
.BMap_container {
  width: 100%;
  height: 100%;
  background-color: rgb(242,242,242);
}
:deep(.map-buoy) {
  position: relative;
  width: 1px;
  height: 1px;
  .icon {
    position: absolute;
    transform: translateX(-50%) translateY(-44px);
    width: 44px;
    height: 44px;
    background: url('@T2/assets/maps/buoy-normal.png') no-repeat center;
    background-size: 100% 100%;
  }
  .icon.alarm {
    background: url('@T2/assets/maps/buoy-alarm.png') no-repeat center;
    background-size: 100% 100%;
  }
  .icon.offline {
    background: url('@T2/assets/maps/buoy-offline.png') no-repeat center;
    background-size: 100% 100%;
  }
}
.left {
  max-width: 17.1875%;
  max-height: 88.93%;
  object-fit: contain;
  position: absolute;
  left: 22px;
  top: 40px;
  z-index: 20;
}
.right {
  max-width: 16.30%;
  max-height: 88.8557%;
  object-fit: contain;
  position: absolute;
  right: 35px;
  top: 40px;
  z-index: 20;
}
</style>